import time
import logging
from aesEnDecryptions.aesEnDecryption import aes_encrypt_b64
from mqtt.mQTTClient import MqttClient
from objects import globalVariable


def assemble_topics():
    topics = []
    topics.append('action' )
    return topics

def mqtt_keson_connect():
    client_no = 'automaticlogonzfh1'
    # 配置日志
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger()
    # MQTT服务器地址和端口
    broker_address = '47.94.80.3'
    broker_port = 61613  # 替换为你的MQTT代理服务器端口
    # MQTT用户名和密码
    username = 'admin'
    password = 'keson-123'
    key = 'keson-123abcdefg'.encode('utf-8')
    will_topic = 'online'
    will_message = '{clientNo:"%s",msg:"0"}' % client_no
    # 铭文加密函数初始化
    will_message_encrypted = aes_encrypt_b64(will_message, key)
    topics = assemble_topics()
    try:
        globalVariable.client_keson = MqttClient(client_no, username, password, topics, will_topic, will_message_encrypted)
        MqttClient.connect(globalVariable.client_keson, broker_address, broker_port, 60)
    except Exception as e:
        logger.error(f'Error connecting to MQTT Broker: {e}')
    # 保持客户端运行
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        logger.info('Exiting...')
